package crp.core.user.domain.repositories;

import com.qwlabs.lang.C2;
import com.qwlabs.lang.S2;
import crp.core.user.domain.models.UserEntity;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import io.quarkus.panache.common.Parameters;

import javax.enterprise.context.ApplicationScoped;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;

import static io.quarkus.panache.common.Parameters.with;

@ApplicationScoped
public class UserRepository implements PanacheRepositoryBase<UserEntity, String> {
    public Stream<UserEntity> findByIds(Collection<String> ids) {
        if (C2.isEmpty(ids)) {
            return Stream.empty();
        }
        return find("id in (:ids)", with("ids", ids)).stream();
    }

    public PanacheQuery<UserEntity> findBy(String keyword) {
        if (S2.isBlank(keyword)) {
            return findAll();
        }
        return find("facultyId in (select id from FacultyEntity where name like :keyword or facultyNo like :keyword) " +
                        " or studentId in (select id from StudentEntity where name like :keyword or studentNo like :keyword)",
                Parameters.with("keyword", "%" + keyword + "%"));

    }

    public Optional<UserEntity> findByFacultyId(String facultyId) {
        return find("facultyId=:facultyId", with("facultyId", facultyId)).firstResultOptional();
    }

    public Optional<UserEntity> findByStudentId(String studentId) {
        return find("studentId=:studentId", with("studentId", studentId)).firstResultOptional();
    }
}
